// panel/index.js, this filename needs to match the one registered in package.json
var path = require('path');
var exec = require('child_process').exec;
var myCopy = Editor.require("packages://native_hotupdate/panel/copy");

//是否已开始生成
var bStartCreate = false;

Editor.Panel.extend({
  // css style for panel
  style: `
    :host { margin: 5px; }
    h2 { color: #f90; }
  `,

  // html template for panel
  template: `
	<hr />
    <div>
		<span>热更地址:</span>
		<ui-input id="remote_url" placeholder="输入热更服务器地址" style="width:80%"></ui-input>
	</div>
	<div style="padding:10px 0px 0px 0px">
		<span>构建模板:</span>
		<ui-select id="muban" value="1">
			<option value="0">jsb-default</option>
			<option value="1">jsb-link</option>
		</ui-select>
	</div>
	<div style="padding:10px 0px 0px 0px">
		<span>版本号:</span>
		<ui-input id="new_version" placeholder="新版本号" value="" style="width:80%"></ui-input>
	</div>
	<div style="padding:10px 0px 0px 0px">
		<span>导出目录:</span>
		<ui-input id="package_dest" placeholder="导出目标目录" value="" style="width:80%"></ui-input>
	</div>
    <hr />
	<div class="layout horizontal around-justified">
	  <ui-button class="green" id=btn>生成</ui-button>
	</div>
  `,

  // element and variable binding
  $: {
    btn: '#btn',
	remoteUrl: '#remote_url',
    muban: '#muban',
	packageDest: '#package_dest',
	newVersion: '#new_version',
  },

  // method executed when template and styles are successfully loaded and initialized
  ready () {
    this.$btn.addEventListener('confirm', () => {
		if(process.env.buildDest === undefined){
			Editor.log("当前没有发布路径");
			Editor.Dialog.messageBox({message:"[错误]:当前没有发布路径,请先构建项目",title:"原生包热更工具"});
			return;
		}
		  
		if (this.$remoteUrl.value.length == 0) {
          Editor.error('[错误]:请先输入热更服务器地址');
		  Editor.Dialog.messageBox({message:"[错误]:请先输入热更服务器地址",title:"原生包热更工具"});
          return;
        }
		
		if (bStartCreate) {
          Editor.warn('[警告]:正在生成热更文件,重复点击无效...');
          return;
        }
		bStartCreate = true;
		
		var child;
		let cmdStr = 'node ' + path.join(Editor.Project.path, 'packages/native_hotupdate/version_generator.js');
		cmdStr += ' -v ' + this.$newVersion.value;
		cmdStr += ' -u ' + this.$remoteUrl.value;
		cmdStr += ' -s ' + process.env.buildDest;
		cmdStr += ' -d ' + path.join(Editor.Project.path,'assets');
		
		child = exec(cmdStr);
		
		child.stdout.on('data',function(data) {
          Editor.log('[详细日志]: ' + data);
        });
		
		child.stderr.on('data',function(data) {
			Editor.error('[错误日志]: ' + data);
		});
		
		child.on('close',function(code) {
			if (parseInt(code) != 0) {
				Editor.log('child process exited with code :' + code);
			}
			// 更新完成后自动关闭creator扩展界面
			Editor.log('热更文件已生成:' + (path.join(Editor.Project.path, "packVersion/bin")));
			this.copyToDestPath();
			bStartCreate = false;
        }.bind(this));
      // Editor.Ipc.sendToMain('热更工具:clicked');
    });
  },
  
  copyToDestPath(){
	  if(this.$packageDest.value.length == 0){
		  Editor.Dialog.messageBox({message:"请填写热更文件打包地址",title:"原生包热更工具"});
		  return;
	  }
	  if(process.env.buildDest === undefined){
		  Editor.log("当前没有发布路径");
		  Editor.Dialog.messageBox({message:"[错误]:当前没有发布路径,请先构建项目",title:"原生包热更工具"});
		  return;
	  }
		var buildDest = process.env.buildDest;
	  myCopy.copy(path.join(buildDest,"assets"),path.join(this.$packageDest.value,"assets/"));
	  myCopy.copy(path.join(buildDest,"src"),path.join(this.$packageDest.value,"src/"));
	  myCopy.copyFile(path.join(Editor.Project.path,'assets/project.manifest'),path.join(this.$packageDest.value,"project.manifest"));
	  myCopy.copyFile(path.join(Editor.Project.path,'assets/version.manifest'),path.join(this.$packageDest.value,"version.manifest"));
  },

  // register your ipc messages here
  messages: {
    'native_hotupdate:hello' (event) {
      this.$label.innerText = 'Hello!';
    },
	'native_hotupdate:build_finish' (event,data) {
      Editor.log("index.js ipc ",data);
    }
  }
});